﻿using System;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnpickupingChkWork : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnpickupingChkWork));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnpickupingChkConsumer())
            {
             
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }
                  

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(500);
                }
            }
        }


        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            OrderSummary order;
            using (var ctx = new HzfyWeiXinEntities())
            {
                order = ctx.ApptOrder.Where(x => x.Id == orderId).
                    Select(x => new OrderSummary
                    {
                        Id = x.Id,
                        OrderNo = x.OrderNo,
                        SumFee = x.SumFee
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
            }

            //执行查询挂号状态操作
            var unpickupChkrequest = new GetOrderStatusRequest();
            unpickupChkrequest.OrderId = order.OrderNo;

            GetOrderStatusResponse unpickupChkResponse;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetRegOrderStatus", unpickupChkrequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                unpickupChkResponse = responseMsg.Content.ReadAsAsync<GetOrderStatusResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("查询挂号1订单状态出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new ConsumedResult
                {
                    Ack = false,
                    Delay = 60*1000
                };
            }

            if (unpickupChkResponse.ResultCode == "1" && unpickupChkResponse.ResultDesc.Contains("未查询到订单挂号信息"))
            {
                //order.OrderStatus = ApptOrderExtensions.OrderStatus.微信退号失败.ToInt32();
                //ctx.SaveChanges();

                //// RMQ 发送退号失败的用户通知
                //var msgProducer = new UserMessageProducer();
                //msgProducer.Publish(new UserMessageMsg
                //{
                //    Type = UserMessageType.退号失败通知,
                //    OrderId = order.Id
                //});

                //order.OrderStatus = ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32();
                //ctx.SaveChanges();
                using (var _ctx = new HzfyWeiXinEntities())
                {
                    SqlParameter[] para =
                    {
                        new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32()),
                        new SqlParameter("@OrderId", order.Id),
                    };
                    _ctx.Database.ExecuteSqlCommand(
                        "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                }

                // RMQ 发送退号成功的用户通知
                var msgProducer = new UserMessageProducer();
                msgProducer.Publish(new UserMessageMsg
                {
                    Type = UserMessageType.退号成功通知,
                    OrderId = order.Id
                });

                if (order.SumFee > 0)
                {
                    // RMQ 执行退费操作
                    var refundingProducer = new OrderRefundingUnpickupSucceedProducer();
                    refundingProducer.Publish(new OrderRefundingUnpickupSucceedMsg
                    {
                        OrderType = Rmq.Center.OrderType.挂号订单,
                        OrderId = order.Id
                    });
                }
            }
            else
            {
                // 查询结果为已退号
                if (unpickupChkResponse.Status == "2" || unpickupChkResponse.Status == "1")
                {
                    //order.OrderStatus = ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32();
                    //ctx.SaveChanges();
                    using (var _ctx = new HzfyWeiXinEntities())
                    {
                        SqlParameter[] para =
                        {
                            new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32()),
                            new SqlParameter("@OrderId", order.Id),
                        };
                        _ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                    }
                    // RMQ 发送退号成功的用户通知
                    var msgProducer = new UserMessageProducer();
                    msgProducer.Publish(new UserMessageMsg
                    {
                        Type = UserMessageType.退号成功通知,
                        OrderId = order.Id
                    });

                    if (order.SumFee > 0)
                    {
                        // RMQ 执行退费操作
                        var refundingProducer = new OrderRefundingUnpickupSucceedProducer();
                        refundingProducer.Publish(new OrderRefundingUnpickupSucceedMsg
                        {
                            OrderType = Rmq.Center.OrderType.挂号订单,
                            OrderId = order.Id
                        });
                    }

                }
                // 查询结果为已取号
                if (unpickupChkResponse.Status == "0")
                {
                    //order.OrderStatus = ApptOrderExtensions.OrderStatus.取号成功.ToInt32();
                    //ctx.SaveChanges();
                    using (var _ctx = new HzfyWeiXinEntities())
                    {
                        SqlParameter[] para =
                        {
                            new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.取号成功.ToInt32()),
                            new SqlParameter("@OrderId", order.Id),
                        };
                        _ctx.Database.ExecuteSqlCommand(
                            "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                    }

                    // RMQ 发送退号失败的用户通知
                    var msgProducer = new UserMessageProducer();
                    msgProducer.Publish(new UserMessageMsg
                    {
                        Type = UserMessageType.退号失败通知,
                        OrderId = order.Id
                    });
                }
            }


            return new ConsumedResult
            {
                Ack = true
            };
        }

        public class OrderSummary
        {
            public int Id { get; set; }
            public string OrderNo { get; set; }
            public decimal? SumFee { get; set; }
        }
    }
}